/*
 *  Copyright (c) 2011, StripBandunk and/or its affiliates. All rights reserved.
 * 
 *       http://stripbandunk.com/
 * 
 *  STRIPBANDUNK PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package stripbandunk.tutorial.jtreehibernate.helper;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stripbandunk.tutorial.jtreehibernate.service.CategoryServiceImpl;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author echo
 */
public class HibernateHelper {

    private static final Logger logger = LoggerFactory.getLogger(HibernateHelper.class);

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            logger.error(ex.getMessage(), ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void init() {
        Session session = HibernateHelper.getSessionFactory().openSession();
        CategoryServiceImpl service = new CategoryServiceImpl(session);

        service.save("Programming");
        service.save("Design");
        service.save("Photographt");
        service.save("Web");
        service.save("Database");
        service.save("Networking");
        service.save("Server");
        service.save("Hardware");
        service.save("Mobile");

        session.close();
    }
}
